$(function () {
  form = layui.form
  layer = layui.layer
  let q = {
    pagenum: 1,	//是	int	页码值
    pagesize: 5,	//是	int	每页显示多少条数据
    cate_id: '',	//否	string	文章分类的 Id
    state: ''
  }
  //渲染列表
  getArticleList()
  function getArticleList() {
    axios({
      url: '/my/article/list',
      method: 'get',
      params: q
    }).then(res => {
      //成功回调
      console.log(res.data)
      let arr = []
      res.data.data.forEach(ele => {
        arr.push(`
      <tr>
      <td>${ele.title}</td>
      <td>${ele.cate_name}</td>
      <td>${formaData(ele.pub_date)}</td>
      <td>${ele.state}</td>
      <td>
      <a href="/article/article-edit.html?id=${ele.Id}" class="layui-btn layui-btn-xs">编辑</a>
        <button data-id="${ele.Id}"  class=" del-btn layui-btn layui-btn-xs layui-btn-danger">删除</button>
      </td>
    </tr>
      `)
      })
      $('tbody').empty().html(arr.join(''))
      renderPage(res.data.total)
    })
  }
  //渲染
  initCateList()
  function initCateList() {
    axios({
      url: '/my/article/cates',
      method: 'get',
    }).then(res => {
      //成功回调
      console.log(res)
      if (res.data.status !== 0) {
        return layer.msg(res.data.message)
      }
      let arr = ['<option value="">请输入文章类别</option>']
      res.data.data.forEach(ele => {
        arr.push(`
      <option value="${ele.Id}">${ele.name}</option>
      `)
      })
      $('[name="cate_id"]').empty().html(arr.join(''))
      form.render()
    })
  }
  // 筛选
  $('#searchForm').on('click', function (e) {
    e.preventDefault()
    q.cate_id = $('[name="cate_id"]').val()
    q.state = $('[name="state"]').val()
    getArticleList()
  })
  //分页
  function renderPage(total) {
    layui.laypage.render({
      elem: 'pageBox',
      count: total,//数据总数，从服务端得到
      limit: q.pagesize,
      curr: q.pagenum,
      layout: ['count', 'limit', 'prev', 'page', 'next', 'refresh', 'skip'],
      limits: [2, 3, 5, 8],
      jump: function (obj, first) {
        //首次不执行
        if (!first) {
          q.pagenum = obj.curr
          q.pagesize = obj.limit
          getArticleList()
        }
      }
    })
  }
  //删除
  $('tbody').on('click', '.del-btn', function () {
    let id = $(this).attr('data-id')
    layer.confirm('是否确定删除?', { icon: 3, title: '提示' }, function (index) {
      axios({
        url: '/my/article/delete/' + id,
        method: 'get'
      }).then(res => {
        //成功回调
        console.log(res)
        if (res.data.status !== 0) {
          return layer.msg(res.data.message)
        }
        layer.msg('恭喜删除成功')
        $('.del-btn').length == 1 && q.pagenum >= 2 && pagenum--
        getArticleList()
      })

      layer.close(index);
    })


  })


})